<?php

namespace App\Admin\Forms;

use App\Clients\CrmClient;
use Dcat\Admin\Form\EmbeddedForm;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;

class SiteSettingForm extends Form
{

    const DISPATCH_OPTIONS = [
        'all' => '全部(分配所有拉取回来的线索)',
        'today' => '当天(只分配当天的新线索,部分平台不能按天拉取,为了避免出现突然拉到老线还给咨询分配霸占咨询的线)',
    ];

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        if (!\Admin::user()->can('setting.change'))
            return $this->response()->error('没有权限');

        if (Arr::has($input, 'crm_account')) {
            $account = Arr::get($input, 'crm_account');
            $originAccount = json_decode(admin_setting('crm_account'), true);

            if ($account['password'] === '__default__') {
                $p = Arr::get($originAccount, 'password');
                $account['password'] = $p;
                Arr::set($input, 'crm_account.password', $p);
            }
            if (!collect($originAccount)->diff($account)->isEmpty()) {
                try {
                    new CrmClient($account);
                } catch (\Exception $exception) {
                    return $this->response()->error($exception->getMessage());
                }
            }
        }

        admin_setting($input);
        return $this
            ->response()
            ->success('保存配置成功');
    }

    /**
     * Build a form here.
     */
    public function form()
    {

        $this->display("推送链接")->value(route('api.clue.access'))
            ->help("配置推送数据时需要添加 `_source_` 字段");

        $this->confirm('保存系统配置', '');

        $this->switch('dispatch_enable', '启动自动分配')->default(1);
        $this->switch('dispatch_overflow_enable', '溢出分配')
            ->help("近一周溢出未分配的表单会在每天指定的时间开始重新分配")
            ->default(0);
        $this->time('dispatch_overflow_time', '溢出重新分配时间')
            ->default("09:20")->saving(function ($val) {
                return substr($val, 0, 5);
            });

        $this->switch('auto_offline', '自动离线')
            ->default(0);
        $this->time('auto_offline_time', '自动离线时间')
            ->default("20:00")
            ->saving(function ($val) {
                return substr($val, 0, 5);
            });

        $this->switch('enable_clue_tags','开启线索标签功能')->default(0);
        $this->switch('enable_files','开启线索附件功能')->default(0);
        $this->switch('enable_clue_api','开启外部线索提交API(巨量购)')->default(0);
//        $this->switch('hidden_clue_source','隐藏咨询"来源"字段')->default(0);

        $this->text("IP_WHITE_LIST", 'IP白名单(多个用,分开),空白表示不限制');


        if (\Admin::user()->can('setting.crm')) {
            $this->embeds('crm_account', 'CRM账号', function (EmbeddedForm $form) {
                $form->url('domain', 'CRM地址')
                    ->help("必须服务器能访问到的地址")
                    ->required();
                $form->html("账号必须包含以下两种权限<br/>1. 网电预约 - 创建预约单(查看 , 创建)<br/>2. 客户基础数据 - 客户媒介来源 (查看)");
                $form->text('username')
                    ->required();
                $form->password('fake_password')->setFormGroupClass('hidden');
                $form->password('password')
                    ->help('默认不显示密码,以防密码泄露,如果不改就不要动!')
                    ->required()
                    ->customFormat(function () {
                        return '__default__';
                    });
            });
        }

        if (\Admin::user()->isAdministrator()) {
            $this->switch("enable_back_up", '开启系统备份')->default(0);
        }

        $this->disableResetButton();
        if (!\Admin::user()->can('setting.change'))
            $this->disableSubmitButton();

    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return admin_setting()->toArray();
    }
}
